<?php
session_start();
//根据session判断用户是否登录
if (!isset($_SESSION['user'])) {
    //未登录则跳转登录页面
    header('Location: back_login.php');
    die;
}
if (empty($_POST)){
    include 'Views/proAdd_View.html';
}else{
    /*添加商品信息到表中*/
    //设置数组映射，使前端提交数据和库中字段名作区分
    $productMap=[
    "pName"=>"productName",
    "pPrice"=>"productPrice",
    "pPic" =>"productPic",
    "pIntro"=>"productIntro"
    ];
    //遍历表单提交的数据
    $addArr=[];
    foreach ($_POST as $k => $v){
            $mapKey=$productMap["$k"];
            $addArr[]="$mapKey = '$v'";
    }
    //拼写图片存放路径
    $fileName = $_FILES['pPic']['name'];
    $addArr["productPic"]="productPic ='imgs/".$fileName."'";
    //处理sql语句
    $addStr=implode(',',$addArr);
    $sqlAdd="INSERT INTO productinfo set ".$addStr;
    $link=require_once "sqlLink.php";
    //执行sql语句，返回状态码
    $res=mysqli_query($link,$sqlAdd);
    //判断执行状态
    if ($res){
        header("location:back_product_list.php");
        die;
    }else{
        echo "<script>alert('数据添加失败！')</script>";
        echo "sql语句：".$sqlAdd;
    }
}

function uplodePic(){
    /* --------- 上传图片 ---------------*/
    $fileName = $_FILES['pPic']['name'];//文件原始名称
    $tmpName = $_FILES['pPic']['tmp_name'];//临时文件路径
    $error = $_FILES['pPic']['error'];
    // 确保文件名是安全的，避免目录遍历攻击
    $fileName = basename($fileName);
    // 检查是否有上传错误
    if ($error !== UPLOAD_ERR_OK) {
        die("图片上传失败，错误代码: " . $error);
    }
    // 移动上传的文件到指定目录
    elseif (!move_uploaded_file($tmpName, "./imgs/{$fileName}")) {
        die("图片上传失败");
    }
}

